package server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import websocket.Framedata;

public class SBroadcastingThread extends Thread
{
    private Collection<SClient> clients;
    private String message;
    private Framedata[] frames = null;
    
    private final static Logger LOGGER = Logger.getLogger(SBroadcastingThread.class
        .getName());

    public SBroadcastingThread(Collection<SClient> clients, String message)
    {
        if (message == null || clients == null)
        {
            throw new IllegalArgumentException();
        }
        this.clients = new ArrayList(clients);
        this.message = message;
    }
    
    public SBroadcastingThread(Collection<SClient> clients, Framedata[] frames)
    {
        if (frames == null || clients == null)
        {
            throw new IllegalArgumentException();
        }
        this.clients = new ArrayList(clients);
        this.frames = frames;
    }
    
    @Override
    public void run()
    {
        super.run();
        
        if (frames == null)
        {
            frames = Framedata.convertMessageToFrames(message);
        }
        
        LOGGER.log(Level.INFO, "Sending message to {0} clients", clients.size());
        
        for(SClient client : clients)
        {
            client.sendMessage(frames);
        }
        LOGGER.log(Level.INFO, "Message sent (passed to clients for sending)");
    }
    
}
